package com.carson.undergo.ui.activity.home

import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.carson.undergo.databinding.UiCanSearchListBinding
import com.carson.undergo.ui.adapter.ContactAdapter
import com.carson.undergo.utils.bean.WanAndroidListBean
import com.model.common.base.activity.BaseActivity
import com.model.common.utils.always.StringUtils
import com.model.common.utils.always.ToastUtils
import me.yokeyword.indexablerv.IndexableLayout

/**
 * Create by Carson on 2022/2/16.
 * Android仿微信好友列表检索功能
 */
class CanSearchListUI : BaseActivity<UiCanSearchListBinding>() {

    private lateinit var mAdapter: ContactAdapter
    private var infoList = ArrayList<WanAndroidListBean>()

    override fun getBundleExtras(extras: Bundle?) {
        infoList = extras?.getSerializable("list") as ArrayList<WanAndroidListBean>
    }

    override fun getViewBinding(): UiCanSearchListBinding =
        UiCanSearchListBinding.inflate(layoutInflater)

    override fun initViewsAndEvents() {
        initAdapter()
    }

    override fun addListener() {
        binding.editSearch.setTextChangedListener {
            val key = StringUtils.getEditString(binding.editSearch)
            if (StringUtils.isEmpty(key)) {
                mAdapter.setDatas(infoList)
            } else {
                mAdapter.setDatas(filterCity(key))
            }
            mAdapter.notifyDataSetChanged()
        }
    }

    private fun initAdapter() {
        binding.indexLayout.setLayoutManager(LinearLayoutManager(mContext))
        mAdapter = ContactAdapter(this)
        binding.indexLayout.setAdapter(mAdapter)
        binding.indexLayout.setOverlayStyle_Center()
        mAdapter.setDatas(infoList)
        //全字母排序。  排序规则设置为：每个字母都会进行比较排序；速度较慢
        binding.indexLayout.setCompareMode(IndexableLayout.MODE_FAST)

        mAdapter.setOnItemContentClickListener { _, originalPosition, currentPosition, entity ->
            val intent = Intent()
            if (originalPosition > 0) {
                intent.putExtra("name", entity.name)
                setResult(RESULT_OK, intent)
                finish()
            } else {
                ToastUtils.showMessage(
                    mContext,
                    "选中Header/Footer:${entity.name} 当前位置:$currentPosition"
                )
            }
        }
    }

    private fun filterCity(key: String?): MutableList<WanAndroidListBean> {
        val data = ArrayList<WanAndroidListBean>()
        for (item in infoList) {
            if (item.name.contains(key.toString())) {
                data.add(item)
            }
        }
        return data
    }
}